package com.aree.caipiao.tool;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

public class WebManager {
	MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
	HttpClient httpClient = new HttpClient(connectionManager);

	public String getSourceCode(String url) {
		return getSourceCode(url, null);
	}

	String encode = "utf-8";

	public boolean saveToFile(File parent, String url) {
		url = adjustURL(url);
		GetMethod get = new GetMethod(url);
		FileOutputStream output = null;
		try {
			httpClient.executeMethod(get);
			File imgFile = new File(parent, url.replaceAll(".*?/", ""));
			output = new FileOutputStream(imgFile);
			output.write(get.getResponseBody());
			output.close();
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (output != null)
				try {
					output.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

		return true;
	}

	public String getSourceCode(String url, Map<String, Object> parameters) {
		url = adjustURL(url);
		int timeout = 35000;
		// httpClient.getHostConfiguration().setProxy("127.0.0.1", 8087);
		HttpClientParams httparams = new HttpClientParams();
		httpClient.setConnectionTimeout(timeout);
		httparams.setSoTimeout(timeout);
		httpClient.setParams(httparams);
		HttpMethodBase postMethod = null;
		if (parameters != null) {
			PostMethod postMethod2 = new PostMethod(url);
			Iterator<String> keyItr = parameters.keySet().iterator();
			while (keyItr.hasNext()) {
				String key = keyItr.next();
				if (parameters.get(key) instanceof String) {
					postMethod2.addParameter(key, (String) parameters.get(key));
				} else if (parameters.get(key) instanceof String[]) {
					for (String s : (String[]) parameters.get(key))
						postMethod2.addParameter(key, s);
				}
			}
			postMethod = postMethod2;
		} else {
			postMethod = new GetMethod(url);
		}
		int statusCode;
		long a = java.lang.Runtime.getRuntime().freeMemory();
		long b = java.lang.Runtime.getRuntime().totalMemory();
		BufferedInputStream input = null;
		InputStream responseBodyAsStream = null;
		try {
			// logger.debug("request URL: " + url);
			statusCode = httpClient.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {
				responseBodyAsStream = postMethod.getResponseBodyAsStream();
				input = new BufferedInputStream(responseBodyAsStream);
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(responseBodyAsStream, "GB2312"));
				StringBuffer sb = new StringBuffer();
				char[] buffer = new char[32 * 4096];
				int bytes_read;
				while ((bytes_read = reader.read(buffer)) != -1)
					sb.append(new String(buffer, 0, bytes_read));
				return new String(sb.toString().getBytes("GB2312"), encode);
			} else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {

				Header locationHeader = postMethod
						.getResponseHeader("location");
				String urlTmp = locationHeader.getValue();
				if (urlTmp != null) {
					if (urlTmp.startsWith("/")) {
						urlTmp = postMethod.getHostConfiguration().getHostURL()
								+ urlTmp;
					}
					System.out
							.println("redirect URL: " + url + "	to	" + urlTmp);
					return getSourceCode(urlTmp);
				} else {
					return "";
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (responseBodyAsStream != null) {
					responseBodyAsStream.close();
				}

				if (input != null) {
					input.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
			postMethod = null;
		}
		return "";

	}

	public String getEncode() {
		return encode;
	}

	public void setEncode(String encode) {
		this.encode = encode;
	}

	/**
	 * 
	 * 保证中文URL也是可以的
	 * 
	 * @since 2012-11-10
	 * @author chengpeng.zhang
	 * @param url
	 * @return
	 */
	private String adjustURL(String url) {
		try {
			url = URLEncoder.encode(url, "utf-8");
			url = url.replaceAll("%2F", "/").replaceAll("%3A", ":")
					.replaceAll("%3F", "?").replaceAll("%3D", "=")
					.replaceAll("%26", "&").replaceAll("%25", "%")
					.replaceAll("%23", "#").replaceAll("%21", "!");
		} catch (UnsupportedEncodingException e) {

		}
		return url;
	}

	public static void main(String[] args) {
		String url = "http://shop33630223.taobao.com/?spm=2013.1.1000126.21.jQ4e8X";
		System.out.println(new WebManager().adjustURL(url));
	}
}
